# Copyright (c) 2009 Peter Corbett
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

import sys
import pygame
import time
import random

class PGCurses:
    COLORS = ((0,0,0),
              (187,0,0),
              (0,187,0),
              (187,187,0),
              (0,0,187),
              (187,0,187),
              (0,187,187),
              (187,187,187),
              (85,85,85),
              (255,85,85),
              (85,255,85),
              (255,255,85),
              (85,85,255),
              (255,85,255),
              (85,255,255),
              (255,255,255))
#    COLORS = ((0,0,0),
#              (205,0,0),
#              (0,205,0),
#              (205,205,0),
#              (0,0,238),
#              (205,0,205),
#              (0,205,205),
#              (229,229,229),
#              (127,127,127),
#              (255,0,0),
#              (0,255,0),
#              (255,255,0),
#              (92,92,255),
#              (255,0,255),
#              (0,255,255),
#              (255,255,255))
    KEYDICT = {
        pygame.K_UP: "UP",
        pygame.K_DOWN: "DOWN",
        pygame.K_LEFT: "LEFT",
        pygame.K_RIGHT: "RIGHT",
        pygame.K_KP0: "KP0",
        pygame.K_KP1: "KP1",
        pygame.K_KP2: "KP2",
        pygame.K_KP3: "KP3",
        pygame.K_KP4: "KP4",
        pygame.K_KP5: "KP5",
        pygame.K_KP6: "KP6",
        pygame.K_KP7: "KP7",
        pygame.K_KP8: "KP8",
        pygame.K_KP9: "KP9",
        pygame.K_ESCAPE: "ESC",
        pygame.K_RETURN: "RETURN",
        pygame.K_BACKSPACE: "BACKSPACE"
        }

    def __init__(self, columns, rows):
        pygame.init()
        self.glyphdict = {}
        self.font = pygame.font.Font("8x13.fon", 16)
        #self.font = pygame.font.SysFont("lucidaconsole", 16)
        r = self.font.render("*", 0, (255,255,255), (0,0,0)).get_rect()
        self.fwidth = r.width
        self.fheight = r.height
        self.columns = columns
        self.rows = rows
        size = (self.columns * self.fwidth, self.rows * self.fheight)
        self.screen = pygame.display.set_mode(size)
        pygame.display.set_caption("Lord Midwinter's Realm")
        self.charmap = [[" " for j in range(self.rows)] for i in range(self.columns)]
        self.fgmap = [[7 for j in range(self.rows)] for i in range(self.columns)]
        self.bgmap = [[0 for j in range(self.rows)] for i in range(self.columns)]

    def refresh(self):
        #rl = []
        for x in range(self.columns):
            for y in range(self.rows):
                #if random.random() > 0.25: continue
                c = self.charmap[x][y]
                if len(c) == 0: c = " "
                if len(c) > 1: c = c[:1]
                s = self.get_glyph(c, self.COLORS[self.fgmap[x][y]], self.COLORS[self.bgmap[x][y]])
                #s = self.font.render(c, False, self.COLORS[self.fgmap[x][y]], self.COLORS[self.bgmap[x][y]])
                self.screen.blit(s, (x * self.fwidth, y * self.fheight))
                #rl.append(pygame.Rect(x*self.fwidth,y*self.fheight,self.fwidth,self.fheight))
        pygame.display.flip()
        #pygame.display.update(rl)
        
    def get_glyph(self, ch, fg, bg):
        if (ch,fg,bg) in self.glyphdict:
            return self.glyphdict[(ch,fg,bg)]
        else:
            s = self.font.render(ch, False, fg, bg)
            self.glyphdict[(ch,fg,bg)] = s
            return s

    def addch(self, x, y, ch, fg, bg=0):
        if x < 0 or y < 0 or x >= self.columns or y >= self.rows:
            return
        self.charmap[x][y] = ch
        self.fgmap[x][y] = fg
        self.bgmap[x][y] = bg

    def setbg(self, x, y, bg):
        if x < 0 or y < 0 or x >= self.columns or y >= self.rows:
            return
        self.bgmap[x][y] = bg

    def addstr(self, x, y, str, fg, bg=0):
        for i in range(len(str)):
            self.addch(x+i, y, str[i], fg, bg)

    def getch(self):
        ch = None
        while ch == None:
            event = pygame.event.wait()
            if event.type == pygame.QUIT:
                sys.exit(0)
            if event.type == pygame.KEYDOWN:
                if event.key in self.KEYDICT:
                    ch = self.KEYDICT[event.key]
                else:
                    u = event.unicode
                    a = u.encode('utf8')
                    if len(a) == 1:
                        ch = a
                #elif event.key in self.KEYDICT:
                #    ch = self.KEYDICT[event.key]
        return ch
        
if __name__=="__main__":
    pgc = PGCurses(80, 25)
    pgc.render()
    time.sleep(1)
    #c = time.clock()
    for y in range(25):
        for x in range(80):
            ch = pgc.getch()
            pgc.addch(x,y,ch,7,0)
            pgc.render()
            #pgc.addch(x,y,
            #              random.choice(("#","_"," ")),
            #              random.randint(0,15),
            #              ##0)
            #              random.randint(0,7))
        #pgc.render()
        #pgc.getch()

    #tt = time.clock() - c
    #print tt / 50
